﻿

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Hisun.Models;

namespace Hisun.View.SCRB
{
    public partial class Scr_Daily_Diliver : System.Web.UI.Page
    {
        private string mypipID;
        int mycostcenterID;
        DateTime dt_myday;
        public string alter;

        HisunDBDataContext db = new HisunDBDataContext();
        protected void Page_Load(object sender, EventArgs e)
        {
            mypipID = HttpUtility.UrlDecode(Request.QueryString["mypip"]);
            dt_myday = DateTime.Parse(HttpUtility.UrlDecode(Request.QueryString["myday"]));
            bindmypip();

            if (!IsPostBack)
            {

                BindEmptyData();
            }
        }

        /// <summary>
        /// 获取当前会计期间
        /// </summary>
        /// <param name="it_date"></param>
        /// <returns></returns>
        private string getAccoutperiod(DateTime it_date)
        {

            var kjqk = (from a in db.TABC_JS_AccountPeriod
                        where a.成本开始日期 <= it_date
                               && a.成本结账日期 >= it_date
                        select a.会计期间ID).Single();

            return kjqk;
        }
        private string getAccoutperiod()
        {
            return getAccoutperiod(this.dt_myday);
        }

        private void bindmypip()
        {
            var mypip = (from a in db.TABC_JS_ProductInProcess
                         where a.中间体ID == mypipID
                         select a).Single();

            mycostcenterID = (int)mypip.作业中心ID;
            string mycostcentername = (from a in db.TABC_JS_CostCenter
                                       where a.作业中心ID == mycostcenterID
                                       select a.作业中心名称).Single();

            Label_CostCenter.Text = mycostcentername;
            Label_PIPNAME.Text = mypip.中间体名称;
            Label_myday.Text = dt_myday.ToShortDateString();


        }

        private string splitbatch(string batch)
        {
            if (batch.IndexOf('/') > 0)
            {
                batch = batch.Split('/')[1];
            }

            return batch;
        }

        private string joinbatch(string batch)
        {
            string join = this.mypipID + "/" + batch;
            return join;
        }

        protected void BindEmptyData()
        {
            var qs = from a in db.TSCRB_JS_BatchInfo
                     join c in db.TSCRB_DM_BatchStatus                     
                     on a.批号类型 equals c.DM                     
                    // join d in db.TSCRB_JS_BatchInfoDetail 
                    // on a.批号 equals d.批号
                     join e in  (from d in db.TSCRB_JS_Out where d.转出时间 == dt_myday select d ) 
                     on a.批号 equals e.批号  into x
                     from y in x.DefaultIfEmpty()
                     where a.中间体ID == mypipID 
                     && (a.批号类型 == "P" || a.批号类型 == "D") 
                     && (y.转出时间 == dt_myday  || (a.转出率 < 1 || a.转出率 ==null))
                     && (a.结束日期 <= dt_myday || a.结束日期 ==null)
                      
                     select new
                     {
                         ID = (y == null ? 0 : y.ID),
                         a.批号,
                         status = (c.状态),
                         转出 = (y!=null),
                         转出率 = (y == null ? (1 - (a.转出率 == null ? 0 : a.转出率)) : (1 - (a.转出率 == null ? 0 : a.转出率)+y.转出系数)),
                         转出系数 = (y == null ? 1 : y.转出系数),
                         转出数量 = (y == null ? 0 : y.转出数量)


                     };
            GridView1.DataSource = qs;
            GridView1.DataBind();
        }
        protected DataTable GetDataFromGrid()
        {

            DataTable dt1 = new DataTable();
            dt1.Columns.Add("ID");
            dt1.Columns.Add("批号");
            dt1.Columns.Add("转出");
            dt1.Columns.Add("转出系数");
            dt1.Columns.Add("转出数量");
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                GridViewRow gRow = GridView1.Rows[i];
                DataRow newRow = dt1.NewRow();
                newRow[0] = GridView1.DataKeys[i].Value;
                newRow[1] = ((TextBox)gRow.FindControl("TextBox1")).Text;
                newRow[2] = ((CheckBox)gRow.FindControl("CheckBox1")).Checked;
                newRow[3] = ((TextBox)gRow.FindControl("TextBox2")).Text;
                newRow[4] = ((TextBox)gRow.FindControl("TextBox3")).Text;

                //newRow[3] = ((TextBox)gRow.FindControl("TextBox3")).Text;
                dt1.Rows.Add(newRow);
            }
            dt1.AcceptChanges();
            return dt1;
        }


        private bool checkbachexist(string batchnumber)
        {
            if (batchnumber.IndexOf('/') < 0)
            {
                batchnumber = joinbatch(batchnumber);
            }
            var q = from a in db.TSCRB_JS_BatchInfo
                    where
                        a.批号 == batchnumber
                    select a;
            if (q.Count() > 0)
            {
                return true;
            }
            return false;

        }

        private void UpdateTransRate(string Batch)
        {
            double sumrate = 0;
            try
            {


              sumrate = (from a in db.TSCRB_JS_Out
                    where a.批号 == Batch
                    select a.转出系数).Sum().Value;

            }
            catch
            {
                sumrate = 0;
            }
            var q = (from a in db.TSCRB_JS_BatchInfo where a.批号 == Batch select a).Single();
            q.转出率 = sumrate;
            db.SubmitChanges();
        }
        protected void Button_Save_Click(object sender, EventArgs e)
        {

          for (int i = 0; i < GridView1.Rows.Count; i++)
          {
              GridViewRow gRow = GridView1.Rows[i];


              if (((CheckBox)gRow.FindControl("CheckBox1")).Checked == true) 
              {
                decimal MyMount = Convert.ToDecimal(((TextBox)gRow.FindControl("TextBox3")).Text);
                if( MyMount > 0)
                {}else
                {
                     alter = "<script>alert('转出数量必须大于零！');</script>";
                      return;
                }
              }

          }


            DataTable dt1 = GetDataFromGrid();
            double 数量;
            double 转出系数;
            foreach (DataRow row in dt1.Rows)
            {
                if (row["ID"].ToString() != "0")
                {
                     

                        var updateout = (from a in db.TSCRB_JS_Out
                                         where a.ID == long.Parse(row["ID"].ToString())
                                         select a).Single();

                        var update = (from a in db.TSCRB_JS_BatchInfo
                                      where a.批号 == updateout.批号
                                      select a).Single();
                        /**   var updatedetail = (from a in db.TSCRB_JS_BatchInfoDetail
                                               where a.批号 == update.批号
                                               orderby a.投入日期 ascending
                                               select a).Take(1).Single();**/

                        if (row["转出"].ToString() == "True")
                        {
                            数量 = 0;
                            转出系数 = 1;
                            double.TryParse(row["转出数量"].ToString(), out 数量);
                            double.TryParse(row["转出系数"].ToString(), out 转出系数);
                            if (update.转出率 > 0 && 转出系数 > (1-update.转出率+updateout.转出系数))
                            {
                                转出系数 = (1 - update.转出率.Value + updateout.转出系数.Value);
                            }
                            else
                            {
                                if (转出系数 > 1 && 转出系数 <= 0)
                                {
                                    转出系数 = 1;
                                }
                            }
                            //if (update.转出率 >= 0 && update.转出率 < 1)
                            //{
                            //    update.转出率 = update.转出率 + 转出系数 - updateout.转出系数;
                            //}
                            //else
                            //{
                            //    update.转出率 = 转出系数;
                            //} 
                                
                            update.批号类型 = "D";
                            updateout.转出数量 = 数量;
                            updateout.转出系数 = 转出系数;
                            updateout.转出时间 = dt_myday;
                            updateout.中间体ID = mypipID;
                            updateout.会计期间ID = getAccoutperiod(dt_myday);
 
                        }
                        else
                        {
                            if ((update.转出率 - updateout.转出系数) <= 0)
                            {

                                update.批号类型 = "P";
                            }
                            db.TSCRB_JS_Out.DeleteOnSubmit(updateout);

                        }


                        db.SubmitChanges();

                        UpdateTransRate(update.批号);
 
                }
                else // out id is null ,   insert a line into  out table
                {
                    if (row["批号"].ToString().Length > 1)
                    {

                        TSCRB_JS_Out updateout = new TSCRB_JS_Out();

                        var update = (from a in db.TSCRB_JS_BatchInfo
                                      where a.批号 == row["批号"].ToString()
                                      select a).Single(); 

                        if (row["转出"].ToString() == "True")
                        {

                            数量 = 0;
                            转出系数 = 1;
                            double.TryParse(row["转出数量"].ToString(), out 数量);
                            double.TryParse(row["转出系数"].ToString(), out 转出系数);
                            if (update.转出率 > 0 && 转出系数 > (1 - update.转出率))
                            {
                                转出系数 = 1 - update.转出率.Value;
                            }

                            if (转出系数 > 1 && 转出系数 <= 0)
                            {
                                转出系数 = 1;
                            }
                            //if (update.转出率 >= 0 && update.转出率 <1)
                            //{
                            //    update.转出率 = update.转出率 + 转出系数;
                            //}
                            //else
                            //{
                            //    update.转出率 = 转出系数;
                            //} 
                            update.批号类型 = "D";
                            updateout.批号 = update.批号;
                            updateout.转出数量 = 数量;
                            updateout.转出系数 = 转出系数;
                            updateout.转出时间 = dt_myday;
                            updateout.中间体ID = mypipID;
                            updateout.会计期间ID = getAccoutperiod(dt_myday);
                            db.TSCRB_JS_Out.InsertOnSubmit(updateout);
                            db.SubmitChanges();

                            UpdateTransRate(update.批号);
 
                            //updatedetail.中止日期 = dt_myday;
                            //update.状态=""
                        }
                         

                      //  db.SubmitChanges();

                    }
                }





            }
            alter = "<script>alert('保存成功！！');</script>";
           // Label_alter.Text += "保存成功";
            BindEmptyData();

        }

        protected void Button_Back_Click(object sender, EventArgs e)
        {
            Response.Redirect("Scrb_Daily_MainPage.aspx?centerid=" + mycostcenterID.ToString() + "&PIPid=" + mypipID);
      
        }
    }
}
